// src/parser.rs

use pest::{error::Error as PestError, Parser};
use pest_derive::Parser;

#[derive(Parser)]
#[grammar = "parser.pest"]
pub struct SysYParser;

pub fn format_error(e: PestError<Rule>) -> String {
    // 从 Error 对象中提取行号
    let line = match e.line_col {
        pest::error::LineColLocation::Pos((l, _)) => l,
        pest::error::LineColLocation::Span((l, _), _) => l,
    };

    // 从 Error 对象中提取期望的规则
    let expected = match &e.variant {
        pest::error::ErrorVariant::ParsingError { positives, .. } => {
            // 将规则列表转换为更易读的格式
            positives
                .iter()
                .map(|rule| format!("{:?}", rule)) // e.g., Rule::Ident -> "Ident"
                .collect::<Vec<_>>()
                .join(", ")
        }
        _ => "unknown error".to_string(),
    };

    format!("Error type B at Line {}: mismatched input expecting {{{}}}", line, expected)
}